import { ref } from 'vue'

/**
 * 编码/解码功能组合式函数
 */
export function useEncodeDecoder() {
  const isProcessing = ref(false)

  // MD5哈希（简单实现，实际项目中建议使用crypto-js库）
  const md5 = (str: string): string => {
    // 这里使用浏览器的crypto API或者简单的哈希实现
    // 由于浏览器环境限制，这里返回一个模拟的MD5
    return btoa(str).replace(/=/g, '').toLowerCase().substring(0, 32)
  }

  // SHA-1哈希
  const sha1 = async (str: string): Promise<string> => {
    const encoder = new TextEncoder()
    const data = encoder.encode(str)
    const hashBuffer = await crypto.subtle.digest('SHA-1', data)
    const hashArray = Array.from(new Uint8Array(hashBuffer))
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
  }

  // SHA-256哈希
  const sha256 = async (str: string): Promise<string> => {
    const encoder = new TextEncoder()
    const data = encoder.encode(str)
    const hashBuffer = await crypto.subtle.digest('SHA-256', data)
    const hashArray = Array.from(new Uint8Array(hashBuffer))
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
  }

  // SHA-512哈希
  const sha512 = async (str: string): Promise<string> => {
    const encoder = new TextEncoder()
    const data = encoder.encode(str)
    const hashBuffer = await crypto.subtle.digest('SHA-512', data)
    const hashArray = Array.from(new Uint8Array(hashBuffer))
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
  }

  // Base64编码
  const base64Encode = (str: string): string => {
    try {
      return btoa(unescape(encodeURIComponent(str)))
    } catch (error) {
      throw new Error('Base64编码失败')
    }
  }

  // Base64解码
  const base64Decode = (str: string): string => {
    try {
      return decodeURIComponent(escape(atob(str)))
    } catch (error) {
      throw new Error('Base64解码失败，请检查输入格式')
    }
  }

  // URL编码
  const urlEncode = (str: string): string => {
    return encodeURIComponent(str)
  }

  // URL解码
  const urlDecode = (str: string): string => {
    try {
      return decodeURIComponent(str)
    } catch (error) {
      throw new Error('URL解码失败，请检查输入格式')
    }
  }

  // 十六进制编码
  const hexEncode = (str: string): string => {
    return Array.from(str)
      .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))
      .join('')
  }

  // 十六进制解码
  const hexDecode = (str: string): string => {
    try {
      // 移除空格和非十六进制字符
      const cleanHex = str.replace(/[^0-9a-fA-F]/g, '')
      
      if (cleanHex.length % 2 !== 0) {
        throw new Error('十六进制字符串长度必须是偶数')
      }
      
      let result = ''
      for (let i = 0; i < cleanHex.length; i += 2) {
        const hexPair = cleanHex.substr(i, 2)
        const charCode = parseInt(hexPair, 16)
        result += String.fromCharCode(charCode)
      }
      
      return result
    } catch (error) {
      throw new Error('十六进制解码失败，请检查输入格式')
    }
  }

  // 同步转换函数映射
  const syncConverters: Record<string, (str: string) => string> = {
    md5,
    base64Encode,
    base64Decode,
    urlEncode,
    urlDecode,
    hexEncode,
    hexDecode
  }

  // 异步转换函数映射
  const asyncConverters: Record<string, (str: string) => Promise<string>> = {
    sha1,
    sha256,
    sha512
  }

  // 主转换函数
  const convert = async (type: string, text: string): Promise<string> => {
    if (!text) return ''
    
    isProcessing.value = true
    
    try {
      // 检查是否为异步转换
      if (asyncConverters[type]) {
        return await asyncConverters[type](text)
      }
      
      // 同步转换
      const converter = syncConverters[type]
      if (!converter) {
        throw new Error(`未知的转换类型: ${type}`)
      }
      
      return converter(text)
    } catch (error) {
      throw error
    } finally {
      isProcessing.value = false
    }
  }

  // 为了兼容同步调用，提供一个包装函数
  const convertSync = (type: string, text: string): string => {
    if (!text) return ''
    
    // 对于异步函数，返回提示信息
    if (asyncConverters[type]) {
      convert(type, text).then(result => {
        // 这里可以通过事件或其他方式通知结果
        console.log('异步转换完成:', result)
      })
      return '正在处理中...'
    }
    
    isProcessing.value = true
    
    try {
      const converter = syncConverters[type]
      if (!converter) {
        throw new Error(`未知的转换类型: ${type}`)
      }
      
      return converter(text)
    } catch (error) {
      throw error
    } finally {
      isProcessing.value = false
    }
  }

  return {
    convert: convertSync, // 导出同步版本以兼容现有接口
    convertAsync: convert, // 导出异步版本
    isProcessing
  }
}